package com.example.myapplication.module_user;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;

import com.example.myapplication.R;
import com.example.myapplication.data.GlobalData;
import com.example.myapplication.data.MessageEvent;
import com.example.myapplication.data.User;
import com.example.myapplication.frags.CommonService_Fragment;
import com.example.myapplication.utils.UserService;

import org.greenrobot.eventbus.EventBus;

public class LoginActivity extends AppCompatActivity {
    private final  int LOGIN_SUCCESS = 1;
    private final  int LOGIN_FAIL = 2;
    EditText userName;
    EditText passWd;
    Handler handler;

    @Override

    @SuppressLint("HandlerLeak")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_page);
        userName = findViewById(R.id.et_userName);
        passWd = findViewById(R.id.et_passwd);
        Context context = this;
        handler = new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what){
                    case LOGIN_SUCCESS:
                        //保存到jwt中
                        GlobalData.jwt = (String) msg.obj;
                        GlobalData.isLogin = true;

                        EventBus.getDefault().post(new MessageEvent(CommonService_Fragment.LOGIN_EVENT));
                        finish();
                        break;
                    case LOGIN_FAIL:
                        EventBus.getDefault().post(new MessageEvent("登录失败！"));
                        break;
                }
            }
        };
        this.findViewById(R.id.btn_login).setOnClickListener(
                new View.OnClickListener() {
                 @Override
                 public void onClick(View view) {
                     User user = new User();
                     user.setName(userName.getText().toString());
                     user.setPwd(passWd.getText().toString());

                     UserService.login(user,handler,LOGIN_SUCCESS,LOGIN_FAIL);
                 }
              }
        );
    }

    // 不登陆就不能用。
    @Override
    protected void onDestroy() {
        super.onDestroy();
      //  System.exit(0);
    }
}